var faceoz = require('ui/faceoz');
var fuel_query_config = require('ui/common/fuel_query/config');
var _current_page_name = 'fuel_query_index';
var _current_field_num = 0;
var _city_id = 0;
var _city_name = '';
var _fuel_type_id = -1;
var _fuel_type_name = 'All Type';
var _current_field_num = 0;
var _current_selected_row = null;
var _is_make_changed = false;
var _selected_field_object = null;
var _data = [];
var _table_name = 'my_fuel';
var _containing_tab = null, _tab_group = null;
//setup database
function _setup_db() {
	var db = Titanium.Database.open(faceoz.database_name);
	var rows = db.execute('SELECT type,name FROM sqlite_master WHERE type=? AND name=? LIMIT 1', 'table', _table_name);
	if (rows.getRowCount() <= 0) {
		_init_fuel_query_tables(db);
	} else {
		rows.close();
	}
	db.close();
}

function _init_fuel_query_tables(db) {
	_init_my_fuel_table(db);
}

function _init_my_fuel_table(db) {
	db.execute('CREATE TABLE IF NOT EXISTS ' + _table_name + '(' + 'id INTEGER PRIMARY KEY,' + 'city_id INTEGER,' + 'fuel_type_id INTEGER,' + 'price TEXT COLLATE NOCASE,' + 'trend_url TEXT COLLATE NOCASE,' + 'created INTEGER)');
}

function _update_my_fuel_table(resultArray) {
	var self = this;
	try {
		var db = Titanium.Database.open(faceoz.database_name);
		for (var i = 0, j = resultArray.length; i < j; i++) {
			var data_rows = db.execute('SELECT * FROM ' + _table_name + ' WHERE city_id=' + resultArray[i].city_id + ' and fuel_type_id=' + resultArray[i].fuel_type_id);
			var data_row_count = data_rows.getRowCount();
			if (data_row_count > 0) {
				Ti.API.info('update '+i);
				db.execute('UPDATE ' + _table_name + ' SET price=?,trend_url=? ' + ' WHERE id=' + data_rows.fieldByName('id'), resultArray[i].price, resultArray[i].trend_url);
			} else {
				Ti.API.info('insert '+i);
				db.execute('INSERT INTO ' + _table_name + ' (city_id,fuel_type_id,price,trend_url)' + 'VALUES(?,?,?,?)', _city_id, resultArray[i].fuel_type_id, resultArray[i].price, resultArray[i].trend_url);
			}
			data_rows.close();
		}
		db.close();
	} catch(err) {
		faceoz.process_simple_error_message(err, _current_page_name + ':_update_my_fuel_table');
		return;
	}
}

/*
 *  select city
 */
function _init_city_field() {
	try {
		var city_value = '';
		var is_required_field = true;
		_current_field_num++;
		var city_name_field = Ti.UI.createTableViewRow({
			city_id : _city_id,
			city_name : _city_name,
			className : 'select_city',
			valueRequired : is_required_field, //for check value
			valuePosition : 3, //for check value
			valueType : 'text', //for check value,
			valuePrompt : 'Please select city.', //for check value
			height : faceoz.default_table_view_row_height,
			hasChild : true
		});
		var city_label_field = Ti.UI.createLabel({
			text : 'City',
			color : faceoz.font_color,
			font : {
				fontSize : faceoz.font_size,
				fontWeight : faceoz.font_weight
			},
			left : 10
		});
		city_name_field.add(city_label_field);
		var city_name_content_required_text_label = Ti.UI.createLabel({
			right : 10,
			height : faceoz.default_table_view_row_height,
			width : faceoz.screen_width / 2,
			textAlign : 'right',
			text : (is_required_field) ? 'Required' : 'Optional',
			opacity : faceoz.hint_text_font_opacity,
			color : faceoz.hint_text_font_color,
			font : {
				fontSize : faceoz.normal_font_size
			}
		});
		city_name_field.add(city_name_content_required_text_label);
		var city_name_content_field = Ti.UI.createLabel({
			right : 10,
			height : ((_city_name === '') || (_city_name === null)) ? faceoz.default_table_view_row_height : 'auto',
			width : faceoz.screen_width / 2,
			textAlign : 'right',
			text : _city_name,
			color : faceoz.selected_value_font_color,
			font : {
				fontSize : faceoz.normal_font_size
			}
		});
		city_name_field.add(city_name_content_field);
		_data.push(city_name_field);
		if ((_city_name === '') || (_city_name === null)) {
			city_name_content_field.visible = false;
		} else {
			city_name_content_required_text_label.visible = false;
		}
	} catch(err) {
		faceoz.process_simple_error_message(err, _current_page_name + ':_init_city_field');
		return;
	}
}

/*
 * select fuel type
 */
function _init_fuel_type_field() {
	try {
		var fuel_type_value = '';
		var is_required_field = true;
		_current_field_num++;
		var fuel_type_field = Ti.UI.createTableViewRow({
			fuel_type_id : _fuel_type_id,
			fuel_type_name : _fuel_type_name,
			className : 'select_fuel_type',
			valueRequired : is_required_field, //for check value
			valuePosition : 3, //for check value
			valueType : 'text', //for check value,
			valuePrompt : 'Please select fuel type.', //for check value
			height : faceoz.default_table_view_row_height,
			hasChild : true
		});
		var fuel_type_label_field = Ti.UI.createLabel({
			text : 'Fuel Type',
			color : faceoz.font_color,
			font : {
				fontSize : faceoz.font_size,
				fontWeight : faceoz.font_weight
			},
			left : 10
		});
		fuel_type_field.add(fuel_type_label_field);
		var fuel_type_content_required_text_label = Ti.UI.createLabel({
			right : 10,
			height : faceoz.default_table_view_row_height,
			width : faceoz.screen_width / 2,
			textAlign : 'right',
			text : (is_required_field) ? 'Required' : 'Optional',
			opacity : faceoz.hint_text_font_opacity,
			color : faceoz.hint_text_font_color,
			font : {
				fontSize : faceoz.normal_font_size
			}
		});
		fuel_type_field.add(fuel_type_content_required_text_label);
		var fuel_type_content_field = Ti.UI.createLabel({
			right : 10,
			height : ((_fuel_type_name === '') || (_fuel_type_name === null)) ? faceoz.default_table_view_row_height : 'auto',
			width : faceoz.screen_width / 2,
			textAlign : 'right',
			text : _fuel_type_name,
			color : faceoz.selected_value_font_color,
			font : {
				fontSize : faceoz.normal_font_size
			}
		});
		fuel_type_field.add(fuel_type_content_field);
		_data.push(fuel_type_field);
		if ((_fuel_type_name === '') || (_fuel_type_name === null)) {
			fuel_type_content_field.visible = false;
		} else {
			fuel_type_content_required_text_label.visible = false;
		}
	} catch(err) {
		faceoz.process_simple_error_message(err, _current_page_name + ':_init_fuel_type_field');
		return;
	}
}

/*
 * query event
 */
function _query_button_click_event() {
	var self = this;
	try {
		var errorString = '';
		if (_city_id == 0) {
			errorString += "Please select city.\n";
		}
		if (errorString != '') {
			alert(errorString);
			return;
		}
		if (Ti.Network.online) {
			faceoz.display_indicator("Querying ...",false);
			var xhr = null;
			xhr = Ti.Network.createHTTPClient({
				enableKeepAlive : false
			});
			xhr.onload = function() {
				try {
					if ((xhr.readyState === 4) && (this.status === 200)) {
						Ti.API.info(this.responseText);
						var resultString = this.responseText.replace('(', '').replace(')', '');
						//resultString = resultString.replace(')','');
						var result = JSON.parse(resultString);
						if (result != undefined && result != null) {
							var xmlText = (result.tb != undefined && result.tb != null) ? result.tb : '';
							var xml = Ti.XML.parseString(xmlText);
							var elements = xml.documentElement.getElementsByTagName("item");
							var j = elements.length;
							var element = null, elementContent = null;
							var resultArray = [];
							for (var i = 0; i < j; i++) {
								var tempVars = {};
								tempVars.city_id = _city_id;
								element = elements.item(i);
								elementContent = element.getElementsByTagName("type").item(0);
								tempVars.fuel_type_id = -2;
								//define a fake value
								switch(_city_id) {
									case 2:
										for (var n = 0, m = fuel_query_config.syd_fuel_type_name_list.length; n < m; n++) {
											if (fuel_query_config.syd_fuel_type_name_list[n] == elementContent.textContent) {
												tempVars.fuel_type_id = fuel_query_config.syd_fuel_type_id_list[n];
												continue;
											}
										}
										//syd
										break;
									case 3:
										for (var n = 0, m = fuel_query_config.mel_fuel_type_name_list.length; n < m; n++) {
											if (fuel_query_config.mel_fuel_type_name_list[n] == elementContent.textContent) {
												tempVars.fuel_type_id = fuel_query_config.mel_fuel_type_id_list[n];
												continue;
											}
										}
										//mel
										break;
									case 8:
										for (var n = 0, m = fuel_query_config.adl_fuel_type_name_list.length; n < m; n++) {
											if (fuel_query_config.adl_fuel_type_name_list[n] == elementContent.textContent) {
												tempVars.fuel_type_id = fuel_query_config.adl_fuel_type_id_list[n];
												continue;
											}
										}
										//adl
										break;
								}

								elementContent = element.getElementsByTagName("price").item(0);
								tempVars.price = elementContent.textContent;
								elementContent = element.getElementsByTagName("trendUrl").item(0);
								tempVars.trend_url = elementContent.textContent;
								resultArray.push(tempVars);
							}
							if (resultArray.length > 0) {
								_update_my_fuel_table(resultArray);
							}
						}

						var fuel_query_result_list_win = require('ui/common/fuel_query/fuel_query_result_list');
						fuel_query_result_list_win = new fuel_query_result_list_win({
							city_id : _city_id,
							fuel_type_id : _fuel_type_id,
							containing_tab : _containing_tab
						});
						//fuel_query_result_list_win.containingTab = _containing_tab;
						_containing_tab.open(fuel_query_result_list_win);
						faceoz.hide_indicator();
					}
				} catch(e) {
					faceoz.hide_indicator();
					faceoz.process_simple_error_message(e, _current_page_name + ':_init_query_button_field - xhr.onload');
				}
			};
			xhr.onerror = function(e) {
				faceoz.hide_indicator();
				faceoz.process_simple_error_message(e, _current_page_name + ':_init_query_button_field - xhr.onerror');
			};
			xhr.setTimeout(faceoz.default_time_out);
			xhr.open('POST', fuel_query_config.host_url, false);
			xhr.send({
				"Mode" : fuel_query_config.query_mode,
				"cid" : _city_id,
				"token" : fuel_query_config.query_token,
				"type" : _fuel_type_id,
				"lang" : "en"
			});
		}
	} catch(err) {
		faceoz.hide_indicator();
		faceoz.process_simple_error_message(err, _current_page_name + ':_init_query_button_field');
		return;
	}
}

function fuel_query_index() {
	var self = this;
	_setup_db();
	var win = Ti.UI.createWindow({
		title : 'Fuel Query'
	});

	_init_city_field();
	_init_fuel_type_field();
	var rightNavBtn = Titanium.UI.createButton({
		title : 'Query',
		style : Titanium.UI.iPhone.SystemButtonStyle.BORDERED
	});
	win.setRightNavButton(rightNavBtn);
	rightNavBtn.addEventListener('click', function() {
		_query_button_click_event();
	});
	var table_view = Ti.UI.createTableView({
		data : _data,
		style : Ti.UI.iPhone.TableViewStyle.GROUPED,
		minRowHeight : faceoz.default_table_view_row_height
	});
	win.add(table_view);
	table_view.addEventListener('click', function(e) {
		if (_containing_tab == null) {
			_containing_tab = win.containingTab;
		}
		_current_selected_row = e.row;
		if (e.row.className == 'select_city') {
			var select_unique_code_from_exist_list_win = require('ui/common/base/select_unique_code_from_exist_list');
			select_unique_code_from_exist_list_win = new select_unique_code_from_exist_list_win({
				title : 'Select City',
				content_id_list : fuel_query_config.city_id_list,
				content_name_list : fuel_query_config.city_name_list,
				content : _city_id,
				content_value : _city_name
			});
			select_unique_code_from_exist_list_win.containingTab = win.containingTab;
			win.containingTab.open(select_unique_code_from_exist_list_win);
		}
		if (e.row.className == 'select_fuel_type') {
			var fuel_type_id_list = [], fuel_type_name_list = [];

			if (_city_id <= 0) {
				alert('Please select city.');
				return;
			} else {
				switch(_city_id) {
					case 2:
						//sydney
						fuel_type_id_list = fuel_query_config.syd_fuel_type_id_list;
						fuel_type_name_list = fuel_query_config.syd_fuel_type_name_list;
						break;
					case 3:
						//mel
						fuel_type_id_list = fuel_query_config.mel_fuel_type_id_list;
						fuel_type_name_list = fuel_query_config.mel_fuel_type_name_list;
						break;
					case 8:
						//adl
						fuel_type_id_list = fuel_query_config.adl_fuel_type_id_list;
						fuel_type_name_list = fuel_query_config.adl_fuel_type_name_list;
						break;
				}
			}
			var select_unique_code_from_exist_list_win = require('ui/common/base/select_unique_code_from_exist_list');
			select_unique_code_from_exist_list_win = new select_unique_code_from_exist_list_win({
				title : 'Select Fuel Type',
				content_id_list : fuel_type_id_list,
				content_name_list : fuel_type_name_list,
				content : _fuel_type_id,
				content_value : _fuel_type_name
			});
			select_unique_code_from_exist_list_win.containingTab = win.containingTab;
			win.containingTab.open(select_unique_code_from_exist_list_win);
		}
	});
	win.addEventListener('focus', function() {
		if (Ti.App.Properties.getBool('update_unique_code_select_uniqute_code_from_exist_list_page_view_flag')) {
			Ti.App.Properties.setBool('update_unique_code_select_uniqute_code_from_exist_list_page_view_flag', false);
			var return_id = parseInt(Ti.App.Properties.getString('update_unique_code_select_uniqute_code_from_exist_list_page_view_id'), 10);
			var return_content = Ti.App.Properties.getString('update_unique_code_select_uniqute_code_from_exist_list_page_view_content');
			switch(_current_selected_row.className) {
				case 'select_city':
					if(_city_id != return_id){
						_fuel_type_id = -1;
					}
					_city_id = return_id;
					_city_name = return_content;
					break;
				case 'select_fuel_type':
					_fuel_type_id = return_id;
					_fuel_type_name = return_content;
					break;
			}

			_current_selected_row.children[_current_selected_row.children.length - 1].text = return_content;
			_current_selected_row.children[_current_selected_row.children.length - 1].visible = true;
			_current_selected_row.children[_current_selected_row.children.length - 2].visible = false;
		}
	});
	return win;
}

module.exports = fuel_query_index;
